// ==UserScript==
// @name         YBFetchAsc
// @namespace    https://bbs.tampermonkey.net.cn/
// @version      0.1.0
// @description  try to take over the world!
// @author       You ScriptCat
// ScriptCat
// @grant GM_xmlhttpRequest
// @match        https://wm.xuanqingkj.cn/jrNJyBfHxQ.php/dashboard*
// ==/UserScript==

(function() {
    'use strict';
    let url_task_log='http://127.0.0.1/index.php/fetcher/takeTask';
    let url_save='http://127.0.0.1/index.php/fetcher/save'
    run()
    function run(){
        let req={
            url:url_task_log+'?t='+new Date().getTime(),
            method :"GET",
            onload:function(xhr){
                console.log(xhr.responseText)
                let urlJSON=JSON.parse(xhr.responseText)
                if(urlJSON){
                    for (let key in urlJSON){
                        fetchData(urlJSON[key],key)
                    }
                }else{
                    setTimeout(run, 1000);
                }
            }
        }
        GM_xmlhttpRequest(req);
    }

    function fetchData(url,key){
        fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                },
            }
        )
            .then(response => {
                if(!response.ok){
                    console.log('!response.ok'+url)
                    return false
                }
                return response.json();
            })
            .then(data => {
                    console.log(48,data.rows.length)
                    let req={
                        url:url_save+'?fetch_log_id='+key+'&remote_total='+data.total,
                        method :"POST",
                        data:'data='+encodeURIComponent(JSON.stringify(data.rows)),
                        headers: {"Content-type": "application/x-www-form-urlencoded"},
                        onload:function(xhr){
                            console.log(54)
                            run()
                        }
                    }
                    GM_xmlhttpRequest(req);
                }
            )
    }
})();